# Results -- change in DVS ~

# libs ----
library(tidyverse)
library(here)
library(tidycensus)


# data ----
data("state_laea")
data("fips_codes")

fips_codes <- fips_codes %>% select(state_name, state, state_code)
fips_codes <- unique(fips_codes)

# Prep treated
countiesT <- read_csv(file = '../data/analysis/analysis.csv') %>% filter(year == 2020) %>% 
  select(state, county, ballots_cast, treat, dem_share_pres)
countiesT <- countiesT %>% left_join(fips_codes)

# Prep Other 
counties <- readRDS(file = '../data/politico_2020/elec2020.Rds')  %>% filter(!(STATE %in% c("Nevada","Montana","Utah","Vermont","Colorado",
                                               "New Jersey","Washington","Hawaii","California")),
                                race == 'president') %>% 
  mutate(dem_share_pres = `D VOTES`/(`D VOTES` + `R VOTES`), 
         ballots_cast = (`D VOTES` + `R VOTES`)/(`D PCT` + `R PCT`) ,
         treat = 0) %>% select(COUNTY, STATE, dem_share_pres, ballots_cast, treat)


names(counties)[1:2] <- c('county','state_name')

counties <- counties %>% left_join(fips_codes)
# fix dc
counties$state_code[2738] <- 11
counties$state[2738] <- 'DC'



# Join and summarize
allcounties <- bind_rows(counties, countiesT)
  
statsum <- allcounties %>% group_by(state, treat) %>% 
  summarize(dem_share_pres = weighted.mean(dem_share_pres, ballots_cast), 
            ballots_cast = sum(ballots_cast),
            state_code = unique(state_code))

statshift <- allcounties %>% mutate(dem_share_shifted = 
                                      ifelse(treat == 1, dem_share_pres - 0.022, dem_share_pres)) %>% 
  group_by(state) %>% 
  summarize(dem_share_pres = weighted.mean(dem_share_shifted, ballots_cast),
            ballots_cast = sum(ballots_cast),
            state_code = unique(state_code))

ak <- tibble(state = 'AK', state_code = '02', dem_share_pres = 153778/(189951+153778),
             ballots_cast = (189951+153778)/(.531+.430))

statshift <- bind_rows(statshift, ak)

names(statshift)[4] <- 'GEOID'

shp <- statshift %>% left_join(state_laea) %>% sf::st_as_sf()

shp %>% ggplot(aes(fill = dem_share_pres)) +
  geom_sf() +
  theme_bw() + 
  scale_fill_gradient2(low = '#e41a1c', high = '#377eb8', na.value = '#4daf4a', midpoint = 0.5,
                       space = 'Lab', guide = 'colourbar',limits = c(0,1)) +
  theme(legend.title = element_blank(), legend.position = c(.84,.09), 
        legend.direction = 'horizontal') + 
  ggsave('../newfig/shiftedmap.png')




